<?php
    require '../../db.php';
    require '../../token.php';
    require '../../tcpdf/tcpdf.php';
    header('Access-Control-Allow-Origin: *');
    date_default_timezone_set("Asia/Kolkata");
    $token = $_GET["token"];
    $timestamp = time();
    $entry_date = date("Y-m-d h:i:s", $timestamp);
    $input = json_decode(file_get_contents('php://input'),true);

    $sql = "SELECT * FROM token WHERE token='".$_GET["token"]."'";
    $result = $conn->query($sql);
    $_GET["emp_id"] = "";
    $_GET["department"] = "";
    if($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
	    $string = decrypt('decrypt',$_GET["token"],$row["key1"],$row["key2"]);
	    $string = explode("$",$string);
	    $_GET["emp_id"] = $string[0];
	    $_GET["department"] = $string[1];
	    break;
    }

    $txt = '{"process": "FRONTEND", "token": "'.$token.'", "action": "'.$_GET["type"].'", "actiontime": "'.$entry_date.'", "department": "'.$_GET["department"].'", "emp_id": "'.$_GET["emp_id"].'", "method": "'.$_SERVER['REQUEST_METHOD'].'", "REMOTE_ADDR": "'.$_SERVER['REMOTE_ADDR'].'"}';
    $myfile = file_put_contents('../../logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
    
    if ($_GET["type"] == "saveDirectPO") {
         $total_value = round($input["total"]);
         $round_value = round(round($input["total"])-$input["total"],2);
         $total_value =  floatval($input["total"])+floatval($round_value);
        $sql = "INSERT INTO purchaseorder (user_no, po_type, vendor_no,broker_name,broker_per, gross_total, gst_total, other_charges,
        net_total, terms_conditions, entry_by, entry_date, discount, requirement_days, delivery_schedule_date, delivery_address, delivery_type,
        booking_location, disc_amt, final_total,billcompany_code, shipcompany_code,rounding) VALUES ('".$_GET["user_no"]."', 'Finish Goods',
        '".$input["vendor_no"]."','".$input["agent_name"]."','".$input["broker_per"]."', '".$input["gross_total"]."', '".$input["gst_total"]."',
        '".$input["other_charges"]."', '".$input["net_total"]."', '".json_encode($input["terms_conditions"])."', '".$_GET["emp_id"]."', 
        '$entry_date', '".$input["discount"]."', '".$input["requirement_days"]."', '".$input["delivery_schedule_date"]."', 
        '".$input["delivery_address"]."', '".$input["delivery_type"]."', '".$input["booking_location"]."', '".$input["dis_amt"]."',
        '".$total_value."','".$input["billcompany_code"]."','".$input["shipcompany_code"]."','".$round_value."')";
        if ($conn->query($sql)) {
            $last_id = $conn->insert_id;
            echo "{\"status\":\"success\"}";

            $materials = $input["materials"];
            for ($i = 0; $i < count($materials); $i++) {
                $material = $materials[$i];
                if ($material["required_for"] == "Own") {
                    $material["client_code"] = "";
                }
                $sql1 = "INSERT INTO po_material (user_no, po_no, po_type, material_code, qty, unit, requirement, quotation_amt, gst, gross_total, tax_total, net_total, required_for, client_code) VALUES ('".$_GET["user_no"]."', '".$last_id."','Finish Goods', '".$material["material_code"]."', '".$material["qty"]."', '".$material["unit"]."', '".$material["requirement"]."', '".$material["rate"]."', '".$material["gst"]."', '".$material["gross_total"]."', '".$material["tax_total"]."', '".$material["net_total"]."', '".$material["required_for"]."', '".$material["client_code"]."')";
                $conn->query($sql1);
            }
        } else {
            echo "{\"status\":\"".$conn->error."\"}";
        }
    } 
    
    else if ($_GET["type"] == "saveIndendPO") {
        $sql = "INSERT INTO purchaseorder (user_no, po_type, vendor_no, gross_total, gst_total, net_total, terms_conditions, entry_by, entry_date, discount, requirement_days, delivery_schedule_date, delivery_address) VALUES ('".$_GET["user_no"]."', 'Finish Goods', '".$input["vendor_no"]."', '".$input["gross_total"]."', '".$input["gst_total"]."', '".$input["net_total"]."', '".json_encode($input["terms_conditions"])."', '".$_GET["emp_id"]."', '$entry_date', '".$input["discount"]."', '".$input["requirement_days"]."', '".$input["delivery_schedule_date"]."', '".$input["delivery_address"]."')";
        if ($conn->query($sql)) {
            $last_id = $conn->insert_id;
            echo "{\"status\":\"success\"}";

            $materials = $input["materials"];
            for ($i = 0; $i < count($materials); $i++) {
                $material = $materials[$i];
                if ($material["required_for"] == "Own") {
                    $material["client_code"] = "";
                }
                $sql1 = "INSERT INTO po_material (user_no, po_no,po_type, material_code, qty, unit, requirement,quotation_no, quotation_amt, gst, gross_total, tax_total, net_total, required_for, client_code, indend_no,po_indend) VALUES ('".$_GET["user_no"]."', '".$last_id."','Finish Goods','".$material["material_code"]."', '".$material["qty"]."', '".$material["unit"]."', '".$material["requirement"]."','".$material["quotation_no"]."', '".$material["quotation_amt"]."', '".$material["gst"]."', '".$material["gross_total"]."', '".$material["gst_total"]."', '".$material["net_total"]."', '".$material["required_for"]."', '".$material["client_code"]."', '".$material["indend_no"]."','Approve')";
                $conn->query($sql1);
                
                $sql2 = "UPDATE finish_indend SET po_indend='Approve' WHERE material_code='".$material["material_code"]."'";
                $conn->query($sql2); 
                
            }
        } else {
            echo "{\"status\":\"".$conn->error."\"}";
        }
    } 
    else if ($_GET["type"] == "saveIndendPONew") {//Modified by devaraj
        $datas = $input["data"];
        $pos = json_decode(json_encode($datas));
        $Po_Group ="FG";
        $last_id=0;
    
        foreach ($pos as $po) {
                $sql = "Select count(*) as count from purchaseorder where Po_Group = '".$Po_Group."' ";
        $result = $conn->query($sql);
        while($row = $result->fetch_assoc()){
              $last_id = $row['count'];
        }
            if($last_id==0){
                $last_id=1;
            } 
            $length = 4;
            
            $total_value = round($po->net_total);
            $round_value = round(round($po->net_total)-$po->net_total,2);
            $total_value =  floatval($po->net_total)+floatval($round_value);
            
            $number = substr(str_repeat(0, $length).$last_id, - $length);
            $PO_NO = $Po_Group."/PURHO/05".$last_id."/2022-23";
            $sql = "INSERT INTO purchaseorder (user_no, po_no, po_type, vendor_no, gross_total, gst_total, net_total, terms_conditions, entry_by,
            entry_date, discount, requirement_days, delivery_schedule_date, delivery_address,department,billcompany_code,shipcompany_code, transport,
            local_transport,purchase_type,currancy,currancy_rate,term_local_transport,Po_Group,Fin_Year,indent_no,rounding,final_total) 
            VALUES ('".$_GET["user_no"]."','".$PO_NO."', 'Raw Material', '".$po->vendor_no."', '".$po->gross_total."', '".$po->gst_total."', 
            '".$po->net_total."', '".json_encode($po->terms_conditions)."', '".$_GET["emp_id"]."', '$entry_date', '".$po->discount."', 
            '".$po->requirement_days."', '".$po->delivery_schedule_date."', '".$po->delivery_address."','".$po->department."',
            '".$po->billcompany_code."','".$po->shipcompany_code."','".$po->transport."','".$po->local_transport."','".$po->purchase_type."',
            '".$po->currancy."','".$po->currancy_rate."','".$po->term_local_transport."','".$Po_Group."','2002-23','".$po->indent_no."'
            ,'".$round_value."','".$total_value."')";
                
              //echo $sql;
               // echo $po->materials;
             if ($conn->query($sql)) {
                 $last_id = $conn->insert_id;
                 $materials =  json_decode(json_encode($po->materials));
                 foreach ($materials as $mat) {
                     //echo $mat->material_code." ".$mat->required_for, "\n";
                     if ($mat->required_for == "Own") {
                        $mat->client_code = "";
                    }
                    $sql1 = "INSERT INTO po_material (user_no, po_no,po_type, material_code, qty, unit, requirement,quotation_no, quotation_amt, gst,
                    gross_total, tax_total, net_total, required_for, client_code, indend_no,po_indend) VALUES
                    ('".$_GET["user_no"]."', '".$last_id."','Raw Material', '".$mat->material_code."', '".$mat->order_qty."',
                    '".$mat->unit."', '".$mat->requirement."','".$mat->quotation_no."', '".$mat->quotation_amt."',
                    '".$mat->gst."', '".$mat->gross_total."', '".$mat->gst_total."', '".$mat->net_total."',
                    '".$mat->required_for."', '".$mat->client_code."', '".$mat->indend_no."','Approve')";
                    $conn->query($sql1);
                
                    $sql2 = "UPDATE finish_indend SET po_indend='Approve' WHERE id='".$mat->id."'";
                    $conn->query($sql2);
                 }
             }
        } 
    
            echo "{\"status\":\"success\"}";
    } 
    /*else if ($_GET["type"] == "getPendingIndend") {
        $output = Array();
        $sql = "SELECT i.*, v.vendor_name, v.email, v.gst_no, v.address_corporate, a.agent_name FROM finish_indend i LEFT JOIN vendor v ON i.vendor_no=v.vendor_no LEFT JOIN agent a ON p.broker_name=a.agent_no WHERE i.user_no='".$_GET["user_no"]."' AND i.status='pending' AND i.indend_no NOT IN (SELECT indend_no FROM po_material WHERE user_no='".$_GET["user_no"]."' AND indend_no !='') GROUP BY i.vendor_no";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                
                $gross_total = 0;
                $gst_total = 0;
                $net_total = 0;
                
                $output1 = Array();
                $sql1 = "SELECT i.*, m.material_type, m.material_subtype, m.material_name, m.grade FROM finish_indend i LEFT JOIN material m ON i.material_code=m.material_code WHERE i.user_no='".$_GET["user_no"]."' AND i.status='pending' AND i.vendor_no='".$row["vendor_no"]."'";
                $result1 = $conn->query($sql1);
                if ($result1->num_rows > 0) {
                    while ($row1 = $result1->fetch_assoc()) {
                        
                        $gross_total += +$row1["gross_total"];
                        $gst_total += +$row1["gst_total"];
                        $net_total += +$row1["net_total"];
                        
                        if ($row["required_for"] !== 'Own') {
                            $sql2 = "SELECT * FROM client WHERE user_no='".$_GET["user_no"]."' AND client_code='".$row1["client_code"]."'";
                            $result2 = $conn->query($sql2);
                            if ($result2->num_rows > 0) {
                                while ($row2 = $result2->fetch_assoc()) {
                                    $row1["client_name"] = $row2["company"];
                                }
                            }
                        } else {
                            $row1["client_code"] = "NA";
                        }
                        
                        $output1[] = $row1;
                    }
                }
                $row["gross_total"] = $gross_total;
                $row["gst_total"] = $gst_total;
                $row["net_total"] = $net_total;
                $row["indends"] = $output1;
                $output[] = $row;
            }
        }
        echo json_encode($output);
    } */
    else if ($_GET["type"] == "getPendingIndend") {
        $output = Array();
        $sql = "SELECT i.*, v.vendor_name, v.email, v.gst_no, v.address FROM finish_indend i LEFT JOIN vendor v ON i.vendor_no=v.vendor_no WHERE    i.status='approve' AND i.indend_no NOT IN (SELECT indend_no FROM po_material WHERE user_no='".$_GET["user_no"]."' AND indend_no !='') ";
        //echo $sql;
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $gross_total = 0;
                $gst_total = 0;
                $net_total = 0;
                
                $output1 = Array();
                $sql1 = "SELECT i.*,m.material_type, m.material_subtype, m.material_name, m.grade FROM finish_indend i LEFT JOIN material m ON i.material_code=m.material_code LEFT JOIN po_material p ON p.indend_no=i.indend_no WHERE   i.status='approve' AND i.po_indend='pending' AND i.vendor_no='".$row["vendor_no"]."'";
                $result1 = $conn->query($sql1);
                if ($result1->num_rows > 0) {
                    while ($row1 = $result1->fetch_assoc()) {
                        
                        $gross_total += +$row1["gross_total"];
                        $gst_total += +$row1["gst_total"];
                        $net_total += +$row1["net_total"];
                        
                        if ($row["required_for"] !== 'Own') {
                            $sql2 = "SELECT * FROM client WHERE user_no='".$_GET["user_no"]."' AND client_code='".$row1["client_code"]."'";
                            $result2 = $conn->query($sql2);
                            if ($result2->num_rows > 0) {
                                while ($row2 = $result2->fetch_assoc()) {
                                    $row1["client_name"] = $row2["company"];
                                }
                            }
                        } else {
                            $row1["client_code"] = "NA";
                        }
                        
                        $output1[] = $row1;
                    }
                }
                $row["gross_total"] = $gross_total;
                $row["gst_total"] = $gst_total;
                $row["net_total"] = $net_total;
                $row["indends"] = $output1;
                $output[] = $row;
            }
        }
        echo json_encode($output);
    }
    else if ($_GET["type"] == "getPendingPO") {
        $output = array();
        $sql = "SELECT p.*, v.vendor_name, v.address_corporate, v.address_factory, v.gst_no, v.location, v.state_code, v.pincode, a.agent_name FROM purchaseorder p LEFT JOIN vendor v ON p.vendor_no=v.vendor_no LEFT JOIN agent a ON p.broker_name=a.agent_no WHERE p.user_no='".$_GET["user_no"]."' AND p.po_type='Finish Goods' AND p.status='Pending'";
        
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {

                $output1 = array();
                $sql1 = "SELECT p.*, m.material_name, m.grade, m.material_subtype FROM po_material p LEFT JOIN material m ON p.material_code=m.material_code WHERE p.po_no='".$row["id"]."'AND  p.po_type='Finish Goods' AND (p.po_indend='Approve' OR p.material_status='pending') GROUP BY p.id";
                $result1 = $conn->query($sql1);
                if ($result1->num_rows > 0) {
                    while ($row1 = $result1->fetch_assoc()) {
                        $output1[] = $row1;
                    }
                }
                $row["materials"] = $output1;
                $output[] = $row;
            }
        }
        echo json_encode($output);
    } else if ($_GET["type"] == "checkPO") {
        $sql = "UPDATE purchaseorder SET status='".$_GET["status"]."', approve_by='".$_GET["emp_id"]."', approve_date='".$entry_date."' WHERE id='".$_GET["id"]."'";
        if ($conn->query($sql)) {
            echo "{\"status\":\"success\"}";
        } else {
            echo "{\"status\":\"".$conn->error."\"}";
        }
    } else if ($_GET["type"] == "getPOLog") {
        $output = array();
        $sql = "SELECT p.*, v.vendor_name, v.address_corporate, v.address_factory, v.gst_no, v.location, v.state_code, v.pincode, a.agent_name FROM purchaseorder p LEFT JOIN vendor v ON p.vendor_no=v.vendor_no LEFT JOIN agent a ON p.broker_name=a.agent_no WHERE p.user_no='".$_GET["user_no"]."' AND p.po_type='Finish Goods' AND p.vendor_no LIKE '%".$_GET["vendor_no"]."' AND DATE(p.entry_date) BETWEEN '".$_GET["from_date"]."' AND '".$_GET["to_date"]."' AND p.status LIKE '%".$_GET["status"]."%'";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {

                $output1 = array();
                $sql1 = "SELECT p.*, m.material_name, m.grade, m.material_subtype FROM po_material p LEFT JOIN material m ON p.material_code=m.material_code WHERE p.user_no='".$_GET["user_no"]."' AND p.po_no='".$row["id"]."' GROUP BY p.id";
                $result1 = $conn->query($sql1);
                if ($result1->num_rows > 0) {
                    while ($row1 = $result1->fetch_assoc()) {
                        $output1[] = $row1;
                    }
                }
                $row["materials"] = $output1;
                $output[] = $row;
            }
        }
        echo json_encode($output);
    } else if ($_GET["type"] == "getRejectedPO") {
        $output = array();
        $sql = "SLELECT * FROM purchaseorder WHERE user_no='".$_GET["user_no"]."' AND po_type='Finish Goods' AND status='Rejected'";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {

                $output1 = array();
                $sql1 = "SELECT p.*, m.material_name, m.grade, m.material_subtype FROM po_material p LEFT JOIN material m ON p.material_code=m.material_code WHERE p.user_no='".$_GET["user_no"]."' AND p.po_no='".$_GET["id"]."' GROUP BY p.id";
                $result1 = $conn->query($sql1);
                if ($result1->num_rows > 0) {
                    while ($row1 = $result1->fetch_assoc()) {
                        $output1[] = $row1;
                    }
                }
                $row["materials"] = $output1;
                $output[] = $row;
            }
        }
        echo json_encode($output);
    } else if ($_GET["type"] == "ammendPO") {
        $sql = "INSERT INTO purchaseorder (user_no, po_type, vendor_no, requirement_days, gross_total, gst_total, net_total, terms_conditions, entry_by, entry_date, discount, delivery_schedule_date, delivery_address) VALUES ('".$_GET["user_no"]."', 'Finish Goods', '".$input["vendor_no"]."', '".$input["requirement_days"]."', '".$input["gross_total"]."', '".$input["gst_total"]."', '".$input["net_total"]."', '".json_encode($input["terms_conditions"])."', '".$_GET["emp_id"]."', '$entry_date', '".$input["discount"]."', '".$input["delivery_schedule_date"]."', '".$input["delivery_address"]."')";
        if ($conn->query($sql)) {
            $last_id = $conn->insert_id;
            echo "{\"status\":\"success\"}";

            $sql = "UPDATE purchaseorder SET status='ammendment' WHERE id='".$input["id"]."'";
            $conn->query($sql);

            $materials = $input["materials"];
            for ($i = 0; $i < count($materials); $i++) {
                $material = $materials[$i];
                $sql1 = "INSERT INTO po_material (user_no, po_no, material_code, qty, unit, requirement, quotation_amt, gst, gross_total, tax_total, net_total, required_for, client_code) VALUES ('".$_GET["user_no"]."', '".$last_id."', '".$material["material_code"]."', '".$material["qty"]."', '".$material["unit"]."', '".$material["requirement"]."', '".$material["quotation_amt"]."', '".$material["gst"]."', '".$material["gross_total"]."', '".$material["tax_total"]."', '".$material["net_total"]."', '".$material["required_for"]."', '".$material["client_code"]."')";
                $conn->query($sql1);
            }
        } else {
            echo "{\"status\":\"".$conn->error."\"}";
        }
    } else if ($_GET["type"] == "getPODetails") {
        $sql = "SELECT p.*, v.vendor_name, v.address_corporate, v.address_factory, v.gst_no, v.location, v.state_code, v.pincode FROM purchaseorder p LEFT JOIN vendor v ON p.vendor_no=v.vendor_no WHERE p.user_no='".$_GET["user_no"]."' AND p.po_type='Finish Goods' AND p.status='approve' AND p.id='".$_GET["id"]."'";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $output1 = array();
                $sql1 = "SELECT p.*, m.material_name, m.grade, m.material_subtype FROM po_material p LEFT JOIN material m ON p.material_code=m.material_code WHERE p.user_no='".$_GET["user_no"]."' AND p.po_no='".$_GET["id"]."' GROUP BY p.id";
                $result1 = $conn->query($sql1);
                if ($result1->num_rows > 0) {
                    while ($row1 = $result1->fetch_assoc()) {
                        $output1[] = $row1;
                    }
                }
                $row["materials"] = $output1;
                $row["terms_conditions"] = json_decode($row["terms_conditions"]);
                echo json_encode($row);
            }
        } else {
            echo "{}";
        }
    }else if($_GET['type'] == 'downloadPOLog'){
        $_GET['filename'] = 'PURCHASE ORDER LOG'; $_GET['pdftype'] = 'landscape'; include("../../pdfimp.php");
        $html.='
        <table cellpadding="5" style="text-align:center;">
            <tr style="background-color:#DDDAD9;">
                <td style="width:7%;">Sr.</td>
                <td style="width:10%;">Date</td>
                <td style="width:7%;">PO No.</td>
                <td style="width:10%;">Vendor Name</td>
                <td style="width:10%;">Broker Name</td>
                <td style="width:10%;">Broker Percentage</td>
                <td style="width:10%;">Discount</td>
                <td style="width:10%;">Gross Total</td>
                <td style="width:7%;">Tax Total</td>
                <td style="width:7%;">Net Total</td>
                <td style="width:9%;">status</td>
            </tr>';
            $i=1;
            $sql = "SELECT p.*, v.vendor_name, v.address_corporate, v.address_factory, v.gst_no, v.location, v.state_code, v.pincode, a.agent_name FROM purchaseorder p LEFT JOIN vendor v ON p.vendor_no=v.vendor_no LEFT JOIN agent a ON p.broker_name=a.agent_no WHERE p.user_no='".$_GET["user_no"]."' AND p.po_type='Finish Goods' AND p.vendor_no LIKE '%".$_GET["vendor_no"]."' AND DATE(p.entry_date) BETWEEN '".$_GET["from_date"]."' AND '".$_GET["to_date"]."' AND p.status LIKE '%".$_GET["status"]."%'";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {

                $output1 = array();
                $sql1 = "SELECT p.*, m.material_name, m.grade, m.material_subtype FROM po_material p LEFT JOIN material m ON p.material_code=m.material_code WHERE p.user_no='".$_GET["user_no"]."' AND p.po_no='".$row["id"]."' GROUP BY p.id";
                $result1 = $conn->query($sql1);
                if ($result1->num_rows > 0) {
                    while ($row1 = $result1->fetch_assoc()) {
                        $output1[] = $row1;
                $row["materials"] = $output1;
                
                 $html.='
                    <tr>
                        <td>'.$i.'</td>
                        <td>'.date('d-m-Y',strtotime($row['entry_date'])).'</td>
                        <td>'.$row["po_no"].'</td>
                        <td style="text-align:left;">'.$row["vendor_name"].'</td>
                        <td>'.$row['agent_name'].'</td>
                        <td>'.$row['broker_per'].'</td>
                        <td>'.$row['discount'].'</td>
                        <td>'.$row["gross_total"].'</td>
                        <td>'.$row["gst_total"].'</td>
                        <td>'.$row['net_total'].'</td>
                        <td>'.$row['status'].'</td>
                    </tr>';
                    $i++;
                    }
                }
            }
        }
            $html.='
        </table>';
        $pdf->writeHTML($html, true, false, false, false, '');
        $pdf->Output('PurchaseOrder.pdf', 'I');
    } else if ($_GET["type"] == "download") {
        $_GET['filename'] = ''; $_GET['pdftype'] = 'onlyheader'; include("../../pdfimp.php");
        $html= "";
        //$sql = "SELECT p.*,q.quotation_no,q.approve_date FROM purchaseorder p LEFT JOIN quotation q ON p.vendor_no=q.vendor_no WHERE p.po_type='Raw Material'  AND p.id='".$_GET["id"]."'";
        $sql = "SELECT p.*, DATE_FORMAT(DATE(p.entry_date),'%d-%m-%Y') as entry_date, v.vendor_name,v.tel_no1,v.email,v.mobile_no, v.address_corporate, v.address_factory, v.gst_no, v.location, v.state_code, v.pincode, s.state_name ,q.quotation_no,q.approve_date FROM purchaseorder p LEFT JOIN vendor v ON p.vendor_no=v.vendor_no LEFT JOIN quotation q ON p.vendor_no=q.vendor_no LEFT JOIN state s ON v.state_code=s.state_code WHERE p.user_no='".$_GET["user_no"]."' AND  p.po_type='Finish Goods'  AND p.id='".$_GET["id"]."'";
        $result = $conn->query($sql);
        $j=1;
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
             
                $html.='<h3 style="text-align:center;">PurchaseOrder</h3>
                        <table border="1" cellpadding="2">
                            <tr>
                                <td style="width:60%;">
                                    <table>
                                        <tr>
                                            <td style="width:100%;"><b>TO</b><br>'.$row['vendor_name'].'<br>'.$row['address_factory'].'</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;"><b>Phone No:</b>'.$row['tel_no1'].'</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;"><b>Email:</b>'.$row['email'].'</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;"><b>Mobile:</b>'.$row['mobile_no'].'</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;"><b>GST No:</b>'.$row['gst_no'].'</td>
                                        </tr>
                                    </table>
                                </td>
                                <td style="width:40%;">
                                    <table>
                                        <tr>
                                            <td style="width:100%;"><b>Purchase Ord. No.:</b>'.$row['po_no'].'</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;"><b>Purchase Ord. Date:</b>'.$row['entry_date'].'</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;"><b>Quotation Ref. No.:</b>'.$row['quotation_no'].'</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;"><b>Quotation Date:</b>'.$row['approve_date'].'</td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                            <tr>
                                <td style="width:100%;"><b>IMPORTANT :</b>  PLS. MENTION OUR G.S.T. & C.S.T. NO. IN YOUR INVOICE/CHALLANS. MATERIAL SH\'D BE DELIVERED TO OUR GOTA-FACTORY BEFORE 4.00 P.M. </td>
                            </tr>
                            <tr>
                                <td style="width:100%;">Dear Sir,<br>Please supply the following item(s) as per your quotation reffered to above and as per terms and condition stated overleaf</td>
                            </tr>
                            <tr style="background-color:#DDDAD9;font-weight:bold; border: solid 1px black">
                                <td style="width:15%;">Item Name</td>
                                <td style="width:10%;">HSN No</td>
                                <td style="width:10%;">Design No</td>
                                <td style="width:15%;">Delivery Date</td>
                                <td style="width:10%;">Qty</td>
                                <td style="width:10%;">Rate</td>
                                <td style="width:15%;">IGST</td>
                                <td style="width:15%;">Total</td>
                            </tr>
                            <tr>
                                <td style="width:15%;"></td>
                                <td style="width:10%;"></td>
                                <td style="width:10%;"></td>
                                <td style="width:15%;"></td>
                                <td style="width:10%;"></td>
                                <td style="width:10%;"></td>
                                <td style="width:15%;"></td>
                                <td style="width:15%;"></td>
                            </tr>
                            <tr>
                                <td style="width:85%;text-align:right;font-weight:bold;">SubTotal</td>
                                <td style="width:15%;"></td>
                            </tr>
                            <tr>
                                <td style="width:85%;text-align:right;font-weight:bold;">Discount</td>
                                <td style="width:15%;">'.$row['discount'].'</td>
                            </tr>
                            <tr>
                                <td style="width:85%;text-align:right;font-weight:bold;">Total</td>
                                <td style="width:15%;"></td>
                            </tr>
                            <tr>
                                <td style="width:15%;border:none;">Order Place By </td>
                                <td style="width:15%;">:</td>
                                <td style="width:15%;border:none;">Advance amount</td>
                                <td style="width:25%;">:</td>
                                <td style="width:15%;border:none;">Credit Days</td>
                                <td style="width:15%;">:</td>
                            </tr>
                             <tr>
                                <td style="width:15%;border:none;">Booking At</td>
                                <td style="width:15%;">:</td>
                                <td style="width:15%;border:none;">Bill In Favour of</td>
                                <td style="width:25%;">:</td>
                                <td style="width:15%;border:none;">Dispatch By</td>
                                <td style="width:15%;">:</td>
                            </tr>
                             <tr>
                                <td style="width:15%;border:none;">Range</td>
                                <td style="width:15%;">:</td>
                                <td style="width:15%;border:none;">Payment Terms</td>
                                <td style="width:25%;">:</td>
                                <td style="width:15%;border:none;">Delivery At</td>
                                <td style="width:15%;">:</td>
                            </tr>
                             <tr>
                                <td style="width:15%;border:none;">Division</td>
                                <td style="width:15%;">:</td>
                                <td style="width:15%;border:none;">Mode of Trans.</td>
                                <td style="width:25%;">:</td>
                                <td style="width:15%;border:none;">Remarks </td>
                                <td style="width:15%;">:</td>
                            </tr>
                             <tr>
                                <td style="width:15%;border:none;">Drug Lic No</td>
                                <td style="width:15%;">:</td>
                                <td style="width:15%;border:none;">CST No:</td>
                                <td style="width:25%;">:</td>
                                <td style="width:15%;border:none;">E.C.C. No.</td>
                                <td style="width:15%;">:</td>
                            </tr>
                            <tr>
                                <td style="width:100%;">
                                    <ol>
                                        <li>Our TIN No.:24075200479 Dt. 14.09.2005 , C.S.T.No. 24575200479: Dt. 14.09.2005, GST No: 24AAACW7013Q1Z2 Dt.  Pan No: AAACW7013Q</li>
                                        <li>Drug License No: 20B-GJ-AD2-76997 (Dt.03/07/2018), New E.C.C.No.: AAACW7013QXM001</li>
                                        <li>Don’t supply if our PO is not signed by authorized signatory.</li>
                                        <li>Please confirm above order & mention our P.O. No. in all Correspondence & documents.</li>
                                        <li>You are responsible for goods delivery to our Godown in proper packing.</li>
                                        <li>We will not pay any charge for extra packing, postage or Forwarding.</li>
                                        <li>Material should be delivered to our GOTA-FACTORY before 4.00 P.M.</li>
                                        <li>Supply of Raw Material should be of latest Mfg Batch with Less No. Of Batches.</li>
                                        <li>Deliver the goods along with Delivery Challans, Gate Pass and Invoice..</li>
                                        <li>If Delivery of goods from outside state the Octroi limit, enclose the Octroi Receipts with the Invoice.</li>
                                        <li>The test report, COA, other valid documents of the batches supplied will be required with the invoice.</li>
                                        <li>Send MTR & other documents only to our factory address.</li>
                                        <li>Kindly mention Manufacturing Date, Expiry Date, Name of Manufacturer in Invoice.</li>
                                        <li>Kindly mentioned our G.S.T & C.S.T No in your invoices/challans.</li>
                                        <li>Kindly update on the minimum available packing for future purchase.</li>
                                        <li>If Quantity of goods supplied will be more than 10% to the PO then we will raise Debit Note.</li>
                                        <li>Supplier is responsible up to the complete testing done in laboratory.</li>
                                        <li>We will raise Debit Note if rates are higher as per mutually confirmed rate.</li>
                                        <li>Supply of Raw Material should be of latest Mfg. Batch, 3 Month old Mfg.Material not Accepted.</li>
                                        <li>Any Raw Material Self Life Minimum 4 Years.</li>
                                    </ol>
                                </td>
                            </tr>
                            <tr>
                                <td style="width:100%;">
                                    <table border="1" cellpadding="2" style="width:50%;">
                                        <tr>
                                            <td style="text-align:center;">Purchase For</td>
                                        </tr>
                                        <tr>
                                            <td style="width:20%;"></td>
                                            <td style="width:30%;"></td>
                                            <td style="width:20%;"></td>
                                            <td style="width:30%;"></td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                            <tr><td style="width:100%;">Thanking You<br>Yours Faithfully,<br>WEST-COAST PHRMACEUTICAL WORKS LTD</td></tr>
                            <tr>
                                <td style="width:100%;">
                                    <table>
                                        <tr>
                                            <td style="width:100%;">Purchase Department</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;">Mobile </td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;">Email</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;">For any further inquiry please contact on above stated no.</td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                            
                            
                            
                        ';
                $html.="</table>";
                
                $pdf->writeHTML($html, true, false, false, false, '');
                $pdf->Output('Po Report.pdf', 'I');
                break;  
            }
        }
    }else if ($_GET["type"] == "downloadPOReport") {
        $_GET['filename'] = ''; $_GET['pdftype'] = 'onlyheader'; include("../../pdfimp.php");
        $html= "";
        $sql = "SELECT p.*, v.vendor_name, v.address_corporate, v.address_factory, v.gst_no, v.location, v.state_code, v.pincode, a.agent_name FROM purchaseorder p LEFT JOIN vendor v ON p.vendor_no=v.vendor_no LEFT JOIN agent a ON p.broker_name=a.agent_no WHERE p.id='".$_GET["id"]."'";
        //$sql = "SELECT p.*,q.quotation_no,q.approve_date FROM purchaseorder p LEFT JOIN quotation q ON p.vendor_no=q.vendor_no WHERE p.po_type='Raw Material'  AND p.id='".$_GET["id"]."'";
        //$sql = "SELECT p.*, DATE_FORMAT(DATE(p.entry_date),'%d-%m-%Y') as entry_date, v.vendor_name,v.tel_no1,v.email,v.mobile_no, v.address_corporate, v.address, v.gst_no, v.location, v.state_code, v.pincode, s.state_name ,q.quotation_no,q.approve_date FROM purchaseorder p LEFT JOIN vendor v ON p.vendor_no=v.vendor_no LEFT JOIN quotation q ON p.vendor_no=q.vendor_no LEFT JOIN state s ON v.state_code=s.state_code WHERE p.user_no='".$_GET["user_no"]."' AND  p.po_type='Raw Material'  AND p.id='".$_GET["id"]."'";
        $result = $conn->query($sql);
        $j=1;
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
             
                $html.='<h3 style="text-align:center;">PurchaseOrder</h3>
                        <table border="1" cellpadding="2">
                            <tr style="background-color:black; color:white;">
                                <td style="width:33%;text-align:center;">Bill To</td>
                                <td style="width:34%;text-align:center;">SHIP TO</td>
                                <td style="width:33%;text-align:center;">P.O NUMBER</td>
                            </tr>
                            <tr>
                                <td style="width:33%;">
                                    <table>
                                        <tr>
                                            <td style="width:100%;font-weight:bold;">West Coast Pharmaceuticals</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;"><b>Location:</b>Opp Sola Bhagwat, Near Prasang Party Plot,,Near Meldi Mata Temple, Meldi Estate,,GOTA,AHMEDABAD INDIA-382481</td>
                                        </tr>
                                    </table>
                                </td>
                                <td style="width:34%;">
                                    <table>
                                        <tr>
                                            <td style="width:100%;font-weight:bold;">'.$row['vendor_name'].'</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;"><b>Location:</b>'.$row['address'].''.$row['address_factory'].'</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;"><b>Email:</b>'.$row['email'].'</td>
                                        </tr>
                                        <tr>
                                            <td style="width:100%;"><b>Mobile No:</b>'.$row['mobile_no'].'</td>
                                        </tr>
                                    </table>
                                </td>
                                <td style="width:33%;">
                                    <table>
                                        <tr>
                                            <td style="width:50%;font-weight:bold;">PO No</td>
                                            <td style="width:50%;">:'.$row['po_no'].'</td>
                                        </tr>
                                        <tr>
                                            <td style="width:50%;font-weight:bold;">PO Type</td>
                                            <td style="width:50%;">:'.$row['po_type'].'</td>
                                        </tr>
                                        <tr>
                                            <td style="width:50%;font-weight:bold;">PO Date</td>
                                            <td style="width:50%;">:'.date('d-m-Y',strtotime($row['entry_date'])).'</td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                        <div></div>
                        <table border="1" cellpadding="2">
                            <tr style="background-color:black; color:white;">
                                <td style="width:20%;text-align:center;">P.O Date</td>
                                <td style="width:20%;text-align:center;">Requisitioner</td>
                                <td style="width:20%;text-align:center;">Shipped Via</td>
                                <td style="width:20%;text-align:center;">F.O.B Point</td>
                                <td style="width:20%;text-align:center;">Terms</td>
                            </tr>
                            <tr>
                                <td style="width:20%;">'.date('d-m-Y',strtotime($row['entry_date'])).'</td>
                                <td style="width:20%;">West Coast Pharmaceuticals</td>
                                <td style="width:20%;"></td>
                                <td style="width:20%;"></td>
                                <td style="width:20%;"></td>
                            </tr>
                        </table>
                        <div></div>
                        <table border="1" cellpadding="2">
                            <tr style="background-color:black; color:white;">
                                <td style="width:10%;text-align:center;">Qty</td>
                                <td style="width:10%;text-align:center;">Unit</td>
                                <td style="width:50%;text-align:center;">Description</td>
                                <td style="width:15%;text-align:center;">Unit Price</td>
                                <td style="width:15%;text-align:center;">Total</td>
                            </tr>';
                        $sql1 = "SELECT * FROM po_material WHERE id='".$_GET["id"]."'";
                        $result1 = $conn->query($sql1);
                        if ($result1->num_rows > 0) {
                            while ($row1 = $result1->fetch_assoc()) {
                            $html.='
                            <tr>
                                <td style="width:10%;">'.$row1['qty'].'</td>
                                <td style="width:10%;">'.$row1['unit'].'</td>
                                <td style="width:50%;"></td>
                                <td style="width:15%;">'.$row1['quotation_amt'].'</td>
                                <td style="width:15%;">'.$row1['gross_total'].'</td>
                            </tr>';
                            }
                        }
                    $sql2 = "SELECT * FROM po_material WHERE id='".$_GET["id"]."'";
                    $result2 = $conn->query($sql1);
                    if ($result2->num_rows > 0) {
                        while ($row2 = $result2->fetch_assoc()) {
                        $html.='
                            <tr>
                                <td rowspan="5" style="width:50%;">
                                    <ul>
                                        <li>Please send two copies of your invoice.</li>
                                        <li>Enter this order in accordance with the prices, terms, delivery method, and specifications listed above</li>
                                        <li>Please notify us immediately if you are unable to ship as specified.</li>
                                        <li>Send all correspondence to:</li>
                                    </ul>
                                </td>
                                <td style="width:35%;">Sub Total</td>
                                <td style="width:15%;">'.$row2['gross_total'].'</td>
                            </tr>
                            <tr>
                                <td style="width:35%;">Sub Total Sales Tax</td>
                                <td style="width:15%;">'.$row2['tax_total'].'</td>
                            </tr>
                            <tr>
                                <td style="width:35%;">Shipping & Handling</td>
                                <td style="width:15%;"></td>
                            </tr>
                            <tr>
                                <td style="width:35%;">Other</td>
                                <td style="width:15%;"></td>
                            </tr>
                            <tr>
                               <td style="width:35%;">Total</td>
                                <td style="width:15%;">'.$row2['net_total'].'</td>
                            </tr>';
                        }
                    }
                        $html.='
                        </table>
                        <div></div>';
                $html.='<table border="1" cellpadding="3">
                            <tr style="background-color:black; color:white;">
                                <td style="width:50%;text-align:center;">Checked By & Digital Signed By</td>
                                <td style="width:50%;text-align:center;">Approved By & Digital Signed By</td>
                            </tr>
                            <tr>
                                <td style="width:50%;" >
                                    <table >
                                        <tr>
                                            <td style="width:25%;">Name</td>
                                            <td style="width:25%;">:'.$row['entry_by'].'</td>
                                            <td rowspan="2" style="width:50%;text-align:right;"><img src="../../upload/pdf/sign.jpg" style="width:50px;height:50px;"> </td>
                                        </tr>
                                        <tr>
                                            <td style="width:25%;">ID</td>
                                            <td style="width:25%;">:</td>
                                        </tr>
                                        <tr>
                                            <td style="width:25%;">Department</td>
                                            <td style="width:25%;">:</td>
                                        </tr>
                                        <tr>
                                            <td style="width:25%;">Date</td>
                                            <td style="width:35%;">:'.date('d-m-Y',strtotime($row['entry_date'])).'</td>
                                            <td style="width:20%;">Time</td>
                                            <td style="width:20%;">:'.date('H:i:s',strtotime($row['entry_date'])).'</td>
                                        </tr>
                                    </table>
                                </td>
                                <td style="width:50%;">
                                    <table>
                                        <tr>
                                            <td style="width:25%;">Name</td>
                                            <td style="width:25%;">:'.$row['approve_by'].'</td>
                                            <td rowspan="3" style="width:50%;text-align:right;"><img src="../../upload/pdf/sign.jpg" style="width:50px;height:50px;"> </td>
                                        </tr>
                                        <tr>
                                            <td style="width:25%;">ID</td>
                                            <td style="width:25%;">:</td>
                                        </tr>
                                        <tr>
                                            <td style="width:25%;">Department</td>
                                            <td style="width:25%;">:</td>
                                        </tr>
                                        <tr>
                                            <td style="width:25%;">Date</td>
                                            <td style="width:35%;">:'.date('d-m-Y',strtotime($row['approve_date'])).'</td>
                                            <td style="width:20%;">Time</td>
                                            <td style="width:20%;">:'.date('H:i:s',strtotime($row['approve_date'])).'</td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>';
                
                
                $pdf->writeHTML($html, true, false, false, false, '');
                $pdf->Output('Po Report.pdf', 'I');
                break;  
            }
        }
    }


} else {
    echo "{\"status\":\"invalid\"}";
}

$conn->close();
?>